<template >
  <div class="phone-bar">
    <span
      class="status-box clearfix"
      :class="currentStatusColor"
      v-show="currentIcon.length > 0"
    >
      <el-dropdown
        style="height:36px;"
        @command="changeCdrStatus"
        trigger="click"
        size="small"
        class="fl importantFontSize"
        v-show="isCallArr.indexOf(getCurrentStatusObj.statusNumber) < 0"
      >
        <div class="status-div">
          <span
            class="status-str el-icon-arrow-down V7_iconfont V7_iconV7tubiao_jiantouxia"
            >{{ getCurrentStatusObj.statusName }}</span
          >
          <el-dropdown-menu slot="dropdown" class="plus-popover">
            <el-dropdown-item
              v-for="status in phonebarList"
              v-show="status.number !== getCurrentStatusObj.statusNumber"
              :key="status.number"
              :command="status"
              class="phone-status-drop"
              >{{ status.name }}</el-dropdown-item
            >
          </el-dropdown-menu>
        </div>
      </el-dropdown>
      <div
        class="fl"
        v-show="isCallArr.indexOf(getCurrentStatusObj.statusNumber) > -1"
      >
        <span class="calling-status"
          >{{ getCurrentStatusObj.statusName }}:</span
        >
        <span class="calling-number">{{ getCurrentStatusObj.extraNumber ? getCurrentStatusObj.hideTel + '-' +  getCurrentStatusObj.extraNumber : getCurrentStatusObj.hideTel }}</span>
      </div>
      <PhoneBarTimers ref="phoneBarTimeRef"></PhoneBarTimers>
    </span>
    <span class="status-invalid type-danger" v-show="currentIcon.length <= 0">{{
      getCurrentStatusObj.statusName || '未连接'
    }}</span>
    <span class="phone-bar-btn" v-show="currentIcon.length > 0">
      <el-tooltip effect="dark" content="外呼" placement="bottom" popper-class="plus-popover">
        <span class="V7_iconfont V7_iconV7tubiao_waihu" @click.stop="getCallList" v-popover:callHistory v-show="currentIcon.indexOf('dialout') > -1"
        ></span>
      </el-tooltip>
      <el-tooltip effect="dark" content="挂机" placement="bottom" popper-class="plus-popover">
        <span class="V7_iconfont V7_iconV7tubiao_guaji" @click.self="handUpClick" v-show="currentIcon.indexOf('hangup') > -1"></span>
      </el-tooltip>
      <el-tooltip effect="dark" content="保持" placement="bottom" popper-class="plus-popover">
        <span class="V7_iconfont V7_iconV7tubiao_baochi" @click.stop="holdOrCancleClick('1')" v-show="currentIcon.indexOf('hold') > -1"></span>
      </el-tooltip>
      <el-tooltip effect="dark" content="取消保持" placement="bottom" popper-class="plus-popover">
        <span class="V7_iconfont V7_iconV7tubiao_quxiaobaochi" @click.stop="holdOrCancleClick('2')" v-show="currentIcon.indexOf('recover') > -1"></span>
      </el-tooltip>
      <el-tooltip effect="dark" content="静音" placement="bottom" popper-class="plus-popover">
        <span class="V7_iconfont V7_iconV7tubiao_jingyin" @click.stop="unmuteOrCancleClick('1')" v-show="currentIcon.indexOf('silence') > -1"></span>
      </el-tooltip>
      <el-tooltip effect="dark" content="取消静音" placement="bottom" popper-class="plus-popover">
        <span class="V7_iconfont V7_iconV7tubiao_shengyin" @click.stop="unmuteOrCancleClick('2')" v-show="currentIcon.indexOf('unmute') > -1"></span>
      </el-tooltip>
      <el-tooltip effect="dark" content="转移" placement="bottom" popper-class="plus-popover">
         <span class="V7_iconfont V7_iconV7tubiao_zhuanyi" v-popover:transferPopoveRef v-show="currentIcon.indexOf('transfer') > -1"></span>
      </el-tooltip>
       <el-tooltip effect="dark" content="接回" placement="bottom" popper-class="plus-popover">
         <span class="V7_iconfont V7_iconV7tubiao_jiehuitonghua" @click.stop="callBackClick" v-show="currentIcon.indexOf('callBack') > -1"></span>
      </el-tooltip>
      <el-tooltip effect="dark" content="咨询" placement="bottom" popper-class="plus-popover">
         <span class="V7_iconfont V7_iconV7tubiao_zixun" v-popover:consultPopoveRef v-show="currentIcon.indexOf('consult') > -1"></span>
      </el-tooltip>
       <el-tooltip effect="dark" content="取消咨询" placement="bottom" popper-class="plus-popover">
         <span class="V7_iconfont V7_iconV7tubiao_quxiaozixun" @click.stop="cancleOrEndConsultClick('cancle')" v-show="currentIcon.indexOf('cancleConsult') > -1"></span>
      </el-tooltip>
     <el-tooltip effect="dark" content="三方通话" placement="bottom" popper-class="plus-popover">
         <span class="V7_iconfont V7_iconV7tubiao_sanfangtonghua" @click.stop="threeCallClick" v-show="currentIcon.indexOf('threeCall') > -1"></span>
      </el-tooltip>
      <el-tooltip effect="dark" content="结束咨询" placement="bottom" popper-class="plus-popover">
         <span class="V7_iconfont V7_iconV7tubiao_quxiaozixun" @click.stop="cancleOrEndConsultClick('end')" v-show="currentIcon.indexOf('endConsult') > -1"></span>
      </el-tooltip>
      <el-tooltip effect="dark" content="咨询转移" placement="bottom" popper-class="plus-popover">
         <span class="V7_iconfont V7_iconV7tubiao_zixunzhuanyi" @click.stop="consultTransferClick" v-show="currentIcon.indexOf('consultTransfer') > -1"></span>
      </el-tooltip>
      <!-- v-show="currentIcon.indexOf('hangup') > -1" -->
      <el-tooltip effect="dark"  content="标签" placement="bottom" v-show="currentIcon.indexOf('tag') > -1" popper-class="plus-popover">
         <span style="display:none" >{{cdrId}}</span>
         <span class="V7_iconfont V7_iconV7tubiao_tianjiabiaoqian" v-popover:tags ></span>
      </el-tooltip>
      <el-tooltip effect="dark" content="满意度" placement="bottom" popper-class="plus-popover">
        <span class="V7_iconfont V7_iconV7tubiao_manyidu-20" @click.stop="satisfactionClick" v-show="currentIcon.indexOf('ivr') > -1"></span>
      </el-tooltip>
      <el-tooltip effect="dark" content="接听" placement="bottom" popper-class="plus-popover">
        <span v-show="dialoutState && answerState" class="V7_iconfont V7_iconV7tubiao_jieting" @click.stop="acceptPhone"></span>
      </el-tooltip>
      <el-tooltip effect="dark" content="键盘" placement="bottom" popper-class="plus-popover">
        <span v-show="currentIcon.includes('DTMF')"  class="V7_iconfont V7_iconV7tubiao_bohaojianpan1" @click.stop="acceptPhone" v-popover:softphone></span>
      </el-tooltip>
    </span>
    <el-popover
      ref="callHistory"
      popper-class="call-popover-wrap plus-popover"
      placement="bottom"
      width="auto"
      trigger="click"
      v-model="callVisible"
      @show="showCallHistoryPopover">
      <CallPopover :callList="callList" @closePopover="closePopover"></CallPopover>
    </el-popover>
    <el-popover
      ref="transferPopoveRef"
      placement="bottom"
      popper-class="plus-popover"
      width="340"
      trigger="click"
      v-model="transferVisible"
      @show="showTransferPopover('transferVisible', 'transferRef')">
      <TransferPopover v-if="currentIcon.indexOf('transfer') > -1" @closePopover="closePopover" module="transfer" ref="transferRef"></TransferPopover>
    </el-popover>
    <el-popover
            ref="consultPopoveRef"
            popper-class="plus-popover"
            placement="bottom"
            width="340"
            trigger="click"
            v-model="consultVisible"
            @show="showTransferPopover('consultVisible', 'consultRef')">
      <TransferPopover @closePopover="closePopover" module="consult" ref="consultRef" @consultingAgentData="consultingAgentData"></TransferPopover>
    </el-popover>
    <el-popover
            ref="tags"
            placement="bottom"
            popper-class="plus-popover"
            width="340"
            trigger="click"
            v-model="tagsShow"
            >
      <div class="tag">
        <el-cascader
            size="mini"
            class="mycascader"
            popper-class="plus-popover"
            v-model="tags"
            :options="options"
            filterable
            @change="cascaderChange"
            @show="cascaderShow"
            :props="{value: '_id', label: 'name', checkStrictly: true, emitPath: false, multiple: true}"
            >
          </el-cascader>
          <el-button  @click="saveTags">保存</el-button>
      </div>
    </el-popover>
    <el-popover
            ref="softphone"
            placement="bottom"
            popper-class="plus-popover"
            trigger="click"
            v-model="softphoneShow"
      >
      <el-input placeholder="输入内容等待2秒后完成发送" disabled clearable v-model="softphoneNumber"></el-input>
      <span style="display:none" >{{cdrId}}</span>
      <ul class="key-up-wrap">
          <li>
              <span @click.stop="keyUp('1')">1</span>
              <span @click.stop="keyUp('2')">2</span>
              <span @click.stop="keyUp('3')">3</span>
          </li>
          <li>
              <span @click.stop="keyUp('4')">4</span>
              <span @click.stop="keyUp('5')">5</span>
              <span @click.stop="keyUp('6')">6</span>
          </li>
          <li>
              <span @click.stop="keyUp('7')">7</span>
              <span @click.stop="keyUp('8')">8</span>
              <span @click.stop="keyUp('9')">9</span>
          </li>
          <li>
              <span @click.stop="keyUp('*')">*</span>
              <span @click.stop="keyUp('0')">0</span>
              <span @click.stop="keyUp('#')" >#</span>
          </li>
      </ul>
    </el-popover>
  </div>
</template>
<script lang="ts">
import PhoneBarTimers from './PhoneBarTimers.vue'
import CallPopover from './CallPopover.vue'
import TransferPopover from './TransferPopover.vue'
import { CtiModule } from '@/store/modules/cti/index'
import { Component, Vue, Watch } from 'vue-property-decorator'
import { timeFormat, commonAction, deepClone } from '@/utils/common'
import WebPhoneSdk from '@/utils/webPhoneSdk'
import PlayVoice from '@/utils/playVoice'

import { TagModule } from '@/store/modules/tag'
import { Base64 } from 'js-base64'
interface StatusData {
  name: string,
  number: string
}
@Component({
  name: 'PhoneBar',
  components: { CallPopover, PhoneBarTimers, TransferPopover }
})
export default class PhoneBar extends Vue {
  [x: string]: any
  private phonebarList: object[] = [{ label: '空闲', value: '0' }, { label: '忙碌', value: '1' }]
  private currentIcon: any[] = []
  private callList: object[] = []
  private isCallArr: string[] = ['2', '3', '4', '6', '7', '10', '11', '12', '13', '14', '15'] // 呼叫中，振铃，通话中, 保持，静音,咨询，三方, 被三方, 监听, 耳语
  private callVisible: boolean = false // 外呼的popover
  private transferVisible: boolean = false // 转接的popover
  private consultVisible: boolean = false // 咨询的popover
  private currentStatusColor: string = 'type-danger' // 默认是红色，未连接或者是未注册
  private preStatusNumber: string = '8' // 上一个状态

  // 是否显示接听
  private showAccept: boolean = false
  private playVoice: any
  private callType: string | null = ''
  private showCallHistoryPopover () { // 外呼popover
    this.callVisible = true
    this.transferVisible = false
    this.consultVisible = false
    this.$nextTick(() => { // popover出来时，自动聚焦
      const pane = document.getElementById('auto_complete_dialout') as HTMLInputElement
      if (pane) {
        const inputNode = pane.getElementsByClassName('el-input__inner')[0] as HTMLInputElement
        if (inputNode) {
          inputNode.value = ''
          inputNode.focus()
        }
      }
    })
  }

  private consultingAgentData (data: string) {
    window.sessionStorage.setItem('currentConsultAgent', data) // 把当前咨询的座席信息存储起来，咨询转移时用得上
  }

  private showTransferPopover (type, typeRef) {
    this[type] = true
    this.callVisible = false
    this.$nextTick(() => {
      (this as any).$refs[typeRef].fetchQueueOnlineAgents()
      console.log((this as any).$refs[typeRef])
    })
  }

  private closePopover () { // 关闭外呼的气泡
    this.callVisible = false
    this.transferVisible = false
    this.consultVisible = false
  }

  private changeCdrStatus (data: StatusData) { // 切换电话条状态
    const actionData = { url: ' /call/action/config/phoneBarStatus/setAgentStatus', method: 'POST', data: { statusNumber: data.number } }
    CtiModule.CtiCommonAction(actionData).then((res: any) => {
      if (res.success) {

        // console.log('=====')
      }
    })
  }

  private getCallList () { // 取当前座席的最近5条的通话记录
    const actionData = { url: '/call/action/cdr/latest', method: 'GET', data: { count: 5 } }
    CtiModule.CtiCommonAction(actionData).then((res: any) => {
      if (res && res.success) {
        const resList = res.list || []
        resList.forEach((item: any) => {
          item.handleStartTime = timeFormat(item.startTime, 'noTime')
          if (item.status === 'ANSWER') { // 已接听
            if (['incoming', 'webcall', 'transfer', 'consultTransfer'].includes(item.callType)) { // 呼入
              item.iconfont = 'V7_iconV7tubiao_huru'
            } else { // 外呼
              item.iconfont = 'V7_iconV7tubiao_tonghua'
            }
          } else if (item.status === 'CALL_TRANSFER') { // 转移
            item.iconfont = 'V7_iconV7tubiao_hujiaozhuanyi'
          } else if (item.status === 'CALL_CONSULT') { // 咨询
            item.iconfont = 'V7_iconV7tubiao_hujiaozixun'
          } else if (item.status === 'CALL_CONSULT_TRANSFER') { // 咨询转移
            item.iconfont = 'V7_iconV7tubiao_jilu-zixunzhuanyi'
          } else if (item.status === 'CALL_THREEWAY') { // 三方
            item.iconfont = 'V7_iconV7tubiao_jilu-sanfangtonghua'
          } else { // 其他未接听状态
            item.iconfont = 'V7_iconV7tubiao_weijietong'
          }
        })
        this.callList = resList
      }
    })
  }

  private handUpClick () { // 点击挂机
    const actionData = { url: '/call/action/biz/hangup', method: 'POST', data: { superUniqueId: this.$store.state.cti.superUniqueId } }
    CtiModule.CtiCommonAction(actionData)
  }

  private holdOrCancleClick (type: string) { // type:1 保持 || type:  2 取消保持
    const actionData = { url: '/call/action/biz/holdOrUnHold', method: 'POST', data: { superUniqueId: this.$store.state.cti.superUniqueId, type } }
    CtiModule.CtiCommonAction(actionData)
  }

  private unmuteOrCancleClick (type: string) { // type:1 静音 || type:  2 取消静音   direction: all (默认写死all,双向静音  in 入方向  out 出方向)
    const actionData = { url: '/call/action/biz/muteOrUnMute', method: 'POST', data: { superUniqueId: this.$store.state.cti.superUniqueId, direction: 'all', type } }
    CtiModule.CtiCommonAction(actionData)
  }

  private satisfactionClick () { // 转满意度
    const actionData = { url: '/call/action/biz/transfer/ivr', method: 'POST', data: { superUniqueId: this.$store.state.cti.superUniqueId, type: 'SATISFACTION' } }
    CtiModule.CtiCommonAction(actionData).then((res: any) => {
      if (res && res.success) {
        console.log('2222')
      }
    })
  }

  private threeCallClick () { // 点击转三方
    const actionData = { url: '/call/action/biz/threeWayCall', method: 'POST', data: { superUniqueId: this.$store.state.cti.superUniqueId } }
    CtiModule.CtiCommonAction(actionData).then((res: any) => {
      if (res && res.success) {
        this.$message({ message: '正在进行三方通话，挂断电话即可退出通话', type: 'success' })
      }
    })
  }

  private cancleOrEndConsultClick (type: string) { // 点击结束咨询或者取消咨询
    const actionData = { url: type === 'cancle' ? '/call/action/biz/cancelConsult' : '/call/action/biz/stopConsult', method: 'POST', data: { superUniqueId: this.$store.state.cti.superUniqueId } }
    CtiModule.CtiCommonAction(actionData).then((res: any) => {
      if (res && res.success) {
        if (type === 'end') {
          this.$message({ message: '咨询结束', type: 'success' })
        }
      }
    })
  }

  private consultTransferClick () { // 点击咨询转移
    const consultAgentData = window.sessionStorage.getItem('currentConsultAgent')
    this.$confirm(`确定要转移通话至 ${consultAgentData}`, '提示', {
      confirmButtonText: '转移',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const actionData = { url: '/call/action/biz/consultTransfer', method: 'POST', data: { superUniqueId: this.$store.state.cti.superUniqueId } }
      CtiModule.CtiCommonAction(actionData).then((res: any) => {
        if (res && res.success) {
          this.$message({ message: `通话已转移至 ${consultAgentData}`, type: 'success' })
        }
      })
    })
  }

  private callBackClick () { // 点击接回
    const actionData = { url: '/call/action/biz/resumeConsult', method: 'POST', data: { superUniqueId: this.$store.state.cti.superUniqueId } }
    CtiModule.CtiCommonAction(actionData).then((res: any) => {
      if (res && res.success) {
        this.$message({ message: '通话已接回', type: 'success' })
      }
    })
  }

  private setCurrentIcon (statusNumber: string, callType: string | null, callEvent: string) { // 处理当前状态下电话条都展示哪些按钮
    const form = window.sessionStorage.getItem('sessionForm')
    let localForm: any = {}
    if (form && form !== 'undefined' && form !== 'null') {
      localForm = JSON.parse(form)
    }
    const value = localForm?.loginType === 'WEBRTC' ? 'DTMF' : null
    if (statusNumber === '0' || statusNumber === '1' || statusNumber === '5' || parseInt(statusNumber, 10) > 100) { // 空闲，忙碌，整理，自定义状态
      this.closePopover()
      return ['dialout'] // 外呼
    } else if (statusNumber === '2' || statusNumber === '3' || statusNumber === '12') { // 呼叫中， 振铃，咨询来电
      if (callType && ['autoDialout', 'incoming', 'transfer', 'consult', 'webcall'].indexOf(callType) > -1) {
        if (statusNumber === '2' || statusNumber === '3') {
          if (callEvent === 'consult') {
            return ['hangup', 'answer'] // 挂断, 接起
          }
          if (callType === 'consult') { // 被咨询方的呼叫振铃状态
            return ['hangup', 'answer'] // 挂断, 接起
          }
          return ['hangup', 'answer', 'tag'] // 挂断, 接起, 标签
        } else {
          return ['hangup', 'answer'] // 挂断，接起
        }
      } else {
        if (statusNumber === '2' || statusNumber === '3') { //  呼叫中， 振铃， 且不是被咨询
          // listen, whisper, loot, breakIn
          if (['listen', 'whisper', 'loot', 'breakIn'].includes((callType as string))) { // 监听, 耳语 抢接, 强插的呼叫振铃状态
            return ['hangup', 'answer'] // 挂断, 接起
          }
          return ['hangup', 'tag']
        }
        return ['hangup'] // 挂断
      }
    } else if (statusNumber === '4') { // 通话中
      if (callEvent === 'consult') { // 点击咨询，等待被咨询方接起时的状态（咨询中）
        return ['hangup', 'cancleConsult', 'tag', value] // 挂断，取消咨询, 标签, 键盘
      } else if (callEvent === 'callBack') { // 咨询中点击取消咨询
        return ['hangup', 'callBack', 'consult', 'tag', value] // 挂断，接回，咨询(可继续咨询其他人), 标签, 键盘
      } else {
        return ['hangup', 'hold', 'silence', 'ivr', 'transfer', 'consult', 'tag', value] // 挂断, 保持， 静音, 满意度，转接，咨询,
      }
    } else if (statusNumber === '6') { // 保持
      return ['hangup', 'recover', 'tag'] // 挂断， 取消保持, 标签
    } else if (statusNumber === '7') { // 静音
      return ['hangup', 'unmute', 'tag'] // 挂断, 取消静音, 标签
    } else if (statusNumber === '10') { // 咨询成功
      if (callEvent === 'callback') { // 点击结束咨询
        return ['hangup', 'callBack', 'consult', 'tag'] // 挂断，接回，咨询(可继续咨询其他人)
      } else { // 咨询接起后，咨询方的状态
        return ['hangup', 'threeCall', 'consultTransfer', 'endConsult', 'tag'] // 挂断, 转三方，咨询转接，结束咨询
      }
    } else if (statusNumber === '11' || statusNumber === '12' || statusNumber === '13') { // 三方 || 咨询接起后，被咨询方的状态 || 被三方
      if (statusNumber === '11') {
        return ['hangup', 'tag']
      }
      return ['hangup'] // 挂断
    } else if (statusNumber === '14' || statusNumber === '15') {
      return ['hangup']
    } else { // 8,9(未连接，失效)
      return [] // 没有icon
    }
  }

  private timeType (statusNumber: string, statusTime: string) {
    if (statusNumber === '5') { // 话后整理
      const oldTime = this.getSecondByDate(statusTime)
      this.$nextTick(() => {
        (this as any).$refs.phoneBarTimeRef.timerTypeChange({ timeType: 'countDown', statusTime: oldTime })
      })
    } else if (statusNumber === '8' || statusNumber === '9') { // 未连接 || 失效，清除定时器
      this.$nextTick(() => {
        (this as any).$refs.phoneBarTimeRef.clearPhonebarTimer()
      })
    } else if (this.preStatusNumber !== statusNumber && this.preStatusNumber !== '8') { // 当前状态和上一个状态不一样 && 上一个状态不是未连接（初始化是未连接）
      this.$nextTick(() => {
        (this as any).$refs.phoneBarTimeRef.timerTypeChange({ timeType: 'timing', statusTime: 0 })
      })
    } else { // 状态一致
      const oldTime = this.getSecondByDate(statusTime)
      this.$nextTick(() => {
        (this as any).$refs.phoneBarTimeRef.timerTypeChange({ timeType: 'timing', statusTime: oldTime })
      })
    }
    this.preStatusNumber = statusNumber
  }

  private getSecondByDate (begin: string) { // 计算相同状态下的时长（eg: 通话中刷新系统，根据后台提供的statusTime）
    const beginDate = new Date(begin)
    const endDate = new Date()
    const diff = endDate.getTime() - beginDate.getTime()
    const second = diff / 1000
    return second || 0
  }

  get getCurrentStatusObj () {
    // 0=> 空闲 1=> 忙碌 2=> 呼叫中 3=>振铃 4 =>通话中 5=> 整理  6=> 保持 7=> 静音 8=> 未连接 9=> 失效 10=> 咨询 11=> 三方  12 => 咨询（被咨询方） 13=>三方(被咨询方) 14=> 监听 15=> 耳语 100+ => 自定义状态
    const statusObj = deepClone(this.$store.state.cti.currentStatusObj)
    if (statusObj && statusObj.extras) {
      try {
        const extrasObj = JSON.parse(Base64.decode(statusObj.extras))
        if (extrasObj && Object.keys(extrasObj).includes('extraNumber')) {
          statusObj.extraNumber = extrasObj.extraNumber || ''
        }
      } catch {
        console.log('错误')
      }
    }
    return statusObj
  }

  @Watch('getCurrentStatusObj', { immediate: true })
  private getCurrentStatusObjChange (statusObj: any) {
    let callType: string | null
    if (statusObj.statusNumber === '2' || statusObj.statusNumber === '3') {
      callType = statusObj.callType
      this.callType = callType
    } else {
      callType = null
      this.initType()
    }
    const orange = ['2', '3'] // 呼叫中, 振铃
    const green = ['4', '6', '7', '10', '11', '12', '13', '14', '15'] // 通话中， 保持，静音, 咨询， 三方, 咨询来电, 被三方
    this.currentStatusColor = statusObj.statusNumber === '0' ? 'type-normal' : orange.indexOf(statusObj.statusNumber) > -1 ? 'type-orange' : green.indexOf(statusObj.statusNumber) > -1 ? 'type-green' : 'type-danger'
    this.currentIcon = this.setCurrentIcon(statusObj.statusNumber, callType, statusObj.callEvent)
    if (statusObj.statusNumber && (['0', '1', '8', '5'].includes(statusObj.statusNumber) || statusObj.statusNumber.length > 2)) {
      this.softphoneShow = false
    }
    this.timeType(statusObj.statusNumber, statusObj.statusTime)
  }

  private beforeMount () {
    this.$getCache('/call/action/general/query', ['phonebarList'], false, true, true).then((data: any) => {
      this.phonebarList = data.phonebarList || [{ label: '空闲', value: '0' }, { label: '忙碌', value: '1' }]
    })
    TagModule.getTagTree().then(res => {
      this.options = TagModule.tagTree
    })
  }

  private acceptPhone () {
    WebPhoneSdk.accept()
  }

  // 自动触发接听
  get answerState () {
    const state = this.showAccept && this.currentIcon.indexOf('answer') > -1
    if (WebPhoneSdk.CallConfig.autoAnswer && state) {
      this.acceptPhone()
    } else {
      if (this.playVoice) {
        if (state) {
          this.playVoice.play()
        } else {
          this.playVoice.pause()
        }
      }
    }
    return state
  }

  @Watch('answerState')
  private answerStateChange (value: boolean) {
    if (!value) {
      if (this.playVoice) {
        this.playVoice.pause()
      }
    }
  }

  get dialoutState () {
    const state = (this.showAccept && !!this.callType)
    const callTypeArr = ['dialout', 'previewDialout']
    if (state && this.callType && callTypeArr.indexOf(this.callType) > -1) {
      this.acceptPhone()
    }
    return state
  }

  private mounted () {
    this.playVoice = new PlayVoice()
    WebPhoneSdk.message = (message: string) => {
      if (message === 'incomingcall') {
        this.showAccept = true
      } else {
        this.showAccept = false
      }
      if (message === 'cancel') {
        this.playVoice.pause()
      }
    }
  }

  private initType () {
    this.callType = null
    this.showAccept = false
  }

  // #region DTMF相关
  private softphoneShow = false
  private softphoneNumber = ''
  private postNumber = ''
  private timer: number|undefined = undefined
  private keyUp (val) {
    this.softphoneNumber += val
    this.postNumber += val
    clearTimeout(this.timer)
    this.timer = setTimeout(() => {
      this.pushNumber()
    }, 2000);
  }

  @Watch('softphoneShow')
  private resetSoftphoneNumber () {
    this.softphoneNumber = ''
    this.postNumber = ''
  }

  @Watch('postNumber')
  private watchPostNumber () {
    if (this.postNumber && this.postNumber.length === 5) { // 五个字符后 触发接口
      this.pushNumber()
    }
  }

  private pushNumber () {
    const data = {
      keyPressed: this.postNumber,
      superUniqueId: this.cdrId
    }
    clearTimeout(this.timer)
    if (!this.postNumber) {
      return
    }
    commonAction({ url: '/call/action/ivr/keypressed', method: 'post', data }).then(res => {
      if (res.success) {
        this.postNumber = ''
      }
    })
  }
  // #endregion

  // #region tag相关
  private tagList = []
  private options = []
  private tagsShow = false
  private tags = []
  private saveTags () {
    const list = deepClone(this.tags) || []
    const arr: any[] = []
    list.forEach(i => {
      arr.push({ _id: i, name: TagModule.tagMap?.get(i).fullName, color: TagModule.tagMap?.get(i).color || '#ccc' })
    })
    const data = {
      cdrId: this.$store.state.cti.superUniqueId,
      tags: arr
    }
    commonAction({ url: '/call/action/cdr/tag', method: 'post', data }).then(res => {
      if (res.success) {
        this.$message.success('添加成功')
      }
    })
  }

  private cascaderShow () {
    //
  }

  // @Watch('$store.state.cti.superUniqueId')
  // private mytest (val) {
  //   console.log(val, 1111)
  // }

  get cdrId () {
    this.tags = []
    this.softphoneNumber = ''
    this.softphoneShow = false
    return this.$store.state.cti.superUniqueId
  }

  private cascaderChange (val) {
    if (val && val.length > 10) {
      this.$message.error('至多输入10个标签')
      this.value = val.splice(0, 10)
    }
  }
  // #endregion
}
</script>
<style scoped lang="stylus">
.phone-bar
  width 100%
  height 100%
  font-size 12px
  display flex
  .status-box, .status-invalid
    display inline-block
    width 198px
    height 36px
    background $c-danger
    border-radius 20px
    color #fff
    margin 10px 0 10px 20px
    line-height 36px
    padding 0 10px
    z-index 2
    font-weight bold
    .status-div
      cursor pointer
      color #fff
    .status-str
      max-width 10em
      text-overflow ellipsis
      display inline-block
      overflow hidden
      white-space nowrap
      font-weight bold
      height 36px
      line-height 36px
      font-size 12px
      &:before
        font-size 12px
        float right
        font-weight bold
        margin-left 4px
  .status-invalid
    width 66px
    text-align center
  .type-danger
    background $c-danger
  .type-normal
    background $c-main
  .type-green
    background $c-green
  .type-orange
    background $c-warn
  .phone-bar-btn
    display inline-block
    height 36px
    line-height 56px
    background #F8FBFF
    border-radius 20px
    line-height 36px
    padding 0 14px 0 30px
    margin 10px 10px 10px -24px
    .V7_iconfont
      padding 10px
      color $fc-gray3
      cursor pointer
      font-size 18px
  .calling-number
    display inline-block
    text-overflow ellipsis
    white-space nowrap
    max-width 7em
    padding-bottom 1px
    overflow hidden
    vertical-align middle
  .calling-status
    display inline-block
    line-height 36px
    margin-right 8px
.phone-status-drop
  max-width 26em
  overflow hidden
  text-overflow ellipsis
  white-space nowrap
.tag
  display: flex
  justify-content: space-between
  .mycascader
    width 80%
    /deep/.el-cascader__tags
      align-items: center
.key-up-wrap li
  margin-top 10px
  span
    width: 60px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    margin-left: 23px;
    display: inline-block;
    font-weight: bold;
    color: #303753;
    border-radius: 2px;
    cursor: pointer;
    &:first-child
      margin-left 0
</style>
